import React, { useContext, useMemo, useState } from "react";
import { ValidationContext, useValidation } from "./Context";
import { Validator } from "./Validator";
import { Controller } from "./Controller";

interface IValidationProviderProps {
    validators?: Record<string,(typeof Validator)>;
    children?: any;
}

export const Provider = ({ validators, children }: IValidationProviderProps) => {
    const prevContext = useContext(ValidationContext);
    const [ nextValidators ] = useState(() => {
        const nextData: any = {
            ...prevContext.validators
        };
        if(validators) {
            const invalidKeys: string[] = [];
            Object.keys(validators).forEach((key) => {
                if(!prevContext.validators[key]) {
                    nextData[key] = validators[key];
                } else {
                    invalidKeys.push(key);
                }
            });
            invalidKeys.length > 0 && console.error(`重复的validation key,请检查配置: ${invalidKeys.join(",")}`);
        }
        return nextData;
    });
    const [ controller ] = useState(() => new Controller({
        validators: nextValidators
    }));
    const nextContext = useMemo(() => ({
        validators: nextValidators,
        controller
    }), [ nextValidators ]);
    
    return (
        <ValidationContext.Provider value={nextContext}>
            {children}
        </ValidationContext.Provider>
    );
};